<template>
    <div :style="{
            opacity: show ? 1 : 0,
            '--bg-url': bgUrl ? ('url(' + bgUrl + ')') : '',
            '--box-url': currentBox ? ('url(' + currentBox + ')') : '',
            // 表格高度控制变量 - 您可以根据需要修改这些值
            '--container-height': '1058px',
            '--table-left': '80px',
            '--table-top': '70px',
            '--table-right': '80px',
            '--table-bottom': '120px',
            '--table-width': '1200px',
            '--table-height': 'calc(var(--container-height) - var(--table-top) - var(--table-bottom))',
            // 按钮默认位置（可在此基础上改）
            '--tab-terran-left': '550px',
            '--tab-terran-top': '40px',
            '--tab-protoss-left': '1090px',
            '--tab-protoss-top': '40px',
            '--tab-zerg-left': '820px',
            '--tab-zerg-top': '40px',
        }" 
        class="tabbed-table" 
        @mouseenter="onMouseEnter"
        @mouseleave="onMouseLeave"
        :class="[{ 'with-bg': true }, currentTab + 'Box']"
    >
            <!-- 关闭按钮：右上角红色圆角 -->
            <button class="close-btn" @click="show = false" aria-label="关闭">×</button>
            
            <button
                v-for="tab in tabs"
                :key="tab.name"
                :class="['tab-btn', 'tab-' + tab.name, { active: currentTab === tab.name }]"
                :style="tabButtonStyle(tab.name)"
                @click="switchTab(tab.name)"
            >
                {{ tab.label }}
            </button>

        <!-- 表格 -->
        <div class="table-wrap" ref="tableWrapRef" v-if="show">
            <table>
                <!-- 页切换动画 -->
                <transition-group name="page" tag="tbody">
                    <tr v-for="(row, idx) in paged" :key="row.country_id + '-' + currentPage">
                        <td class="center">{{ rankIndex(idx) }}</td>
                        <td class="country-name" :title="row.country_name">{{ row.country_name }}</td>
                        <td class="strong" :title="String(row.country_area)">{{ row.country_area + ' 城' }}</td>
                        <td class="points" 
                            :title="String(Array.isArray(row.player_list) 
                            ? row.player_list.reduce((s, p) => s + Number(p.point || 0), 0) 
                            : 0)"
                        >
                            {{ Array.isArray(row.player_list) ? row.player_list.reduce((s, p) => s + Number(p.point || 0), 0) : 0 }}
                        </td>
                        <td>
                            <div class="players">
                                <div class="tags">
                                    <div v-for="p in row.player_list" :key="p.userid_platform" class="tag"
                                        :title="`${p.player_name || p.userid_platform} · 城市 ${p.area ?? 0}`">
                                        <img v-if="p.avatar" :src="p.avatar" alt="avatar" class="avatar" @error="handleAvatarError($event, p.avatar)" />
                                        <div v-else class="avatar-fallback">
                                            {{ (p.player_name || p.userid_platform).slice(0, 1) }}
                                        </div>
                                        <div class="info">
                                            <div class="name" :title="p.player_name || p.userid_platform">
                                                {{ p.player_name || p.userid_platform }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>

                    <!-- 空态 -->
                    <tr v-if="!loading && filtered.length === 0" key="empty">
                        <td colspan="5" class="empty">暂无数据</td>
                    </tr>
                </transition-group>
            </table>
        </div>

        <!-- 加载/错误蒙版 -->
        <div v-if="loading" class="overlay">
            <div class="spinner"></div>
            <div>加载中...</div>
        </div>
        <div v-else-if="error" class="overlay error">
            {{ error }}
        </div>
        
        <!-- 分页条（手动翻页） -->
        <div class="pager" v-if="false">
            <div class="left">
                共 <b>{{ filtered.length }}</b> 个国家 ·
                第 <b>{{ currentPage }}</b> / <b>{{ totalPages }}</b> 页 ·
                当前：<b>{{tabs.find(t => t.name === currentTab)?.label}}</b>
            </div>
            <div class="right">
                <button class="btn" :disabled="totalPages <= 1" @click="prevPage">上一页</button>
                <button class="btn" :disabled="totalPages <= 1" @click="nextPage">下一页</button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { handleAvatarError } from '@/utils/playerBox';

import getApi from '@/api/modules/get'
import eventBus from 'vue3-eventbus';

import bgUrl from '@/assets/xinJi/images/mapTable/background.png';
import terranBox from '@/assets/xinJi/images/mapTable/backgroundBox_terran.png'
import zergBox from '@/assets/xinJi/images/mapTable/backgroundBox_zerg.png'
import protossBox from '@/assets/xinJi/images/mapTable/backgroundBox_protoss.png'

const props = defineProps({
    gameId: { type: Number, default: 0 },
    pageSize: { type: Number, default: 10 },
})

const show = ref(false)

const tabs = ref([
    { name: 'terran', label: '人族' },
    { name: 'protoss', label: '神族' },
    { name: 'zerg', label: '虫族' }
])
const currentTab = ref(tabs.value[0].name)

const loading = ref(false)
const error = ref('')
const cache = ref({ terran: null, protoss: null, zerg: null })
const time = ref(null);

function open() { show.value = true }
function close() { show.value = false }
defineExpose({ open, close, refresh })

// 当前族对应的底图
const currentBox = computed(() => {
    switch (currentTab.value) {
        case 'terran':
            return terranBox
        case 'protoss':
            return protossBox
        case 'zerg':
            return zergBox
        default:
            return terranBox
    }
})

// 当前种族数据
const filtered = computed(() =>
    Array.isArray(cache.value[currentTab.value]) ? cache.value[currentTab.value] : []
)

// 分页
const currentPage = ref(1)
const totalPages = computed(() => {
    const n = filtered.value.length
    return Math.max(1, Math.ceil(n / props.pageSize))
})
const paged = computed(() => filtered.value)
function rankIndex(idxInPage) {
    return idxInPage + 1
}
function nextPage() {
    if (totalPages.value <= 1) return
    currentPage.value = currentPage.value >= totalPages.value ? 1 : currentPage.value + 1
}
function prevPage() {
    if (totalPages.value <= 1) return
    currentPage.value = currentPage.value <= 1 ? totalPages.value : currentPage.value - 1
}

// 为每个按钮提供可独立控制的定位与尺寸（通过 CSS 变量覆盖）
function tabButtonStyle(name) {
    const n = String(name)
    return {
        position: 'absolute',
        left: `var(--tab-${n}-left, 20px)`,
        top: `var(--tab-${n}-top, 20px)`,
        width: `var(--tab-${n}-width, var(--tab-width, 220px))`,
        height: `var(--tab-${n}-height, var(--tab-height, 50px))`,
        fontSize: `var(--tab-${n}-font-size, var(--tab-font-size, 18px))`,
        padding: `var(--tab-${n}-padding, var(--tab-padding, 6px 12px))`,
        opacity: 0
    }
}

// 拉取数据
async function fetchList(race) {
    loading.value = true
    error.value = ''
    try {
        const params = { game_id: props.gameId, race }
        const resp = await getApi.getCountryClans(params)
        
        const payload = resp?.data ?? resp
        const json = Array.isArray(payload) ? payload : (Array.isArray(payload?.data) ? payload.data : [])

        const normalized = json.map((row) => ({
            country_id: row.country_id,
            country_name: row.country_name ?? '',
            country_area: Number(row.country_area ?? 0),
            player_list: Array.isArray(row.player_list)
                ? row.player_list.map((p) => ({
                    userid_platform: String(p.userid_platform || ''),
                    avatar: p.avatar || '',
                    player_name: p.player_name || '',
                    area: Number(p.area ?? 0),
                    point: Number(p.point ?? 0)
                }))
                : []
        }))

        normalized.sort((a, b) => b.country_area - a.country_area)
        cache.value[race] = normalized
        currentPage.value = 1 // 新数据重置页码
    } catch (e) {
        error.value = e?.message || '请求失败'
    } finally {
        loading.value = false
    }
}

// 预加载底图，避免切换时闪烁
function preloadImages(srcs) {
    try {
        (srcs || []).forEach((src) => {
            if (!src) return
            const img = new Image()
            img.decoding = 'async'
            img.src = src
        })
    } catch (_) {
        // ignore
    }
}

// 自动循环滚动
const tableWrapRef = ref(null)
let rafId = 0
let scrolling = false
let userInteracting = false
let lastTs = 0
let scrollAccumulator = 0
let wheelTimer = 0
const SCROLL_SPEED = 20 // 放慢：每秒滚动像素（px/s）

function stepScroll(ts) {
    if (!scrolling) return
    if (!lastTs) lastTs = ts
    const dt = (ts - lastTs) / 1000 // s
    lastTs = ts

    // 按时间累加，避免 <1px/帧 的丢失
    scrollAccumulator += SCROLL_SPEED * dt
    const delta = Math.floor(scrollAccumulator)
    if (delta > 0) {
        scrollAccumulator -= delta
        const el = tableWrapRef.value
        if (el) {
            const max = el.scrollHeight - el.clientHeight
            if (max > 0) {
                if (el.scrollTop + delta >= max - 1) {
                    el.scrollTop = 0
                } else {
                    el.scrollTop += delta
                }
            }
        }
    }
    rafId = requestAnimationFrame(stepScroll)
}

function startAutoScroll(resetPosition = true) {
    stopAutoScroll()
    const el = tableWrapRef.value
    if (el && resetPosition) el.scrollTop = 0
    scrolling = true
    lastTs = 0
    scrollAccumulator = 0
    rafId = requestAnimationFrame(stepScroll)
}

function stopAutoScroll() {
    scrolling = false
    if (rafId) cancelAnimationFrame(rafId)
    rafId = 0
}

function resumeAutoScrollIfEligible() {
    if (show.value && !loading.value && filtered.value.length > 0) {
        startAutoScroll(false) // 从当前停留位置继续滚动
    }
}

// 交互
function switchTab(name) {
    currentTab.value = name
    currentPage.value = 1
    refresh()
}

function refresh() {
    fetchList(currentTab.value)
}

// 鼠标进入/离开组件时控制自动隐藏计时器
function onMouseEnter() {
    if (time.value) clearTimeout(time.value)
}
function onMouseLeave() {
    if (!show.value) return
    if (time.value) clearTimeout(time.value)
    time.value = setTimeout(() => (show.value = false), 10000)
}

// 生命周期
onMounted(() => {
    // 预加载所有背景资源
    preloadImages([bgUrl, terranBox, protossBox, zergBox])

    // 用户滚动交互：按下/滚轮/触摸时暂停，松开恢复
    const el = tableWrapRef.value
    const onDragStart = () => { userInteracting = true; stopAutoScroll() }
    const onDragEnd = () => { userInteracting = false; resumeAutoScrollIfEligible() }
    const onWheel = () => {
        userInteracting = true
        stopAutoScroll()
        if (wheelTimer) clearTimeout(wheelTimer)
        wheelTimer = setTimeout(() => {
            userInteracting = false
            resumeAutoScrollIfEligible()
        }, 1200)
    }

    if (el) {
        el.addEventListener('mousedown', onDragStart)
        el.addEventListener('wheel', onWheel, { passive: true })
        el.addEventListener('touchstart', onDragStart, { passive: true })
    }
    window.addEventListener('mouseup', onDragEnd)
    window.addEventListener('touchend', onDragEnd)

    // 清理
    onUnmounted(() => {
        if (el) {
            el.removeEventListener('mousedown', onDragStart)
            el.removeEventListener('wheel', onWheel)
            el.removeEventListener('touchstart', onDragStart)
        }
        window.removeEventListener('mouseup', onDragEnd)
        window.removeEventListener('touchend', onDragEnd)
        if (wheelTimer) clearTimeout(wheelTimer)
    })
})

watch([() => filtered.value.length, () => props.pageSize], () => {
    if (currentPage.value > totalPages.value) currentPage.value = totalPages.value
})

watch(show, (newValue, oldValue) => {
    if (newValue) {
        refresh()
        clearTimeout(time.value)
        time.value = setTimeout(() => show.value = false, 10000);
    }
    else {
        clearTimeout(time.value)
    }
}, { immediate: true })

// 数据就绪且显示时可启动自动滚动；隐藏或加载时停止
watch([
    () => show.value,
    () => loading.value,
    () => filtered.value.length,
], ([visible, isLoading, len]) => {
    if (visible && !isLoading && len > 0 && !userInteracting) {
        startAutoScroll()
    } else {
        stopAutoScroll()
    }
})

onUnmounted(() => {
    stopAutoScroll()
})
</script>

<style scoped lang="less">
/* 固定尺寸 + 半透明白色毛玻璃外框 */
.tabbed-table {
    
    /* 使用 CSS 变量控制容器尺寸 */
    width: var(--container-width, 1411px);
    height: var(--container-height, 1058px);
    border: 1px solid #ddd;
    overflow: hidden;
    background: transparent;
    /* 使用整体背景图 */
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    position: relative;
}

/* 右上角关闭按钮 */
.close-btn {
    position: absolute;
    top: 20px;
    left: 1350px;
    width: 40px;
    height: 40px;
    border-radius: 999px;
    border: none;
    outline: none;
    background: #ef4444; /* 红色 */
    color: #fff;
    font-weight: 800;
    font-size: 24px;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
    z-index: 20;
    pointer-events: auto;
    box-shadow: 0 2px 6px rgba(0,0,0,.25);
}
.close-btn:hover { background: #dc2626; }
.close-btn:active { transform: translateY(1px); }

/* 整个组件使用背景图 */
.tabbed-table.with-bg {
    position: relative;
}

.tabbed-table.with-bg::before {
    content: '';
    position: absolute;
    inset: 0;
    border-radius: inherit;
    /* 两张底图同时显示：族框 + 整体背景 */
    background-image: var(--box-url), var(--bg-url);
    /* 通过 --box-size 控制族框大小（默认 90% 等比） */
    background-size: var(--box-size, 95% auto), 100% auto;
    background-position: left top, center;
    background-repeat: no-repeat, no-repeat;
    z-index: 0;
}

/* 内容层级在背景图之上 */
.tabbed-table.with-bg>* {
    position: relative;
    z-index: 1;
}

/* 覆盖整个组件的加载/错误蒙版（挂在 .tabbed-table 下） */
.tabbed-table > .overlay {
    position: absolute;
    inset: 0;
    background: rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(8px);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    font-weight: bold;
    z-index: 5;
    pointer-events: auto;
}
.tabbed-table > .overlay.error { color: #dc2626; }
.tabbed-table > .overlay .spinner {
    width: 40px;
    height: 40px;
    border: 4px solid #ddd;
    border-top-color: #3b82f6;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 10px;
}

/* 顶部 tabs */
.tabs {
    display: flex;
    align-items: center;
    padding: 8px;
    gap: 8px;
    border-bottom: 1px solid #e5e7eb;
    background: rgba(255, 255, 255, .5);

    button {
        padding: 8px 18px;
        border: 1px solid #e5e7eb;
        background: #fff;
        cursor: pointer;
        border-radius: 8px;
        font-weight: 600;
        transition: all .15s;

        &:hover {
            border-color: #3b82f6;
        }

        &.active {
            background: #3b82f6;
            color: #fff;
            border-color: #3b82f6;
            box-shadow: 0 6px 16px rgba(59, 130, 246, .25);
        }
    }

    .toolbar-right {
        margin-left: auto;

        .refresh {
            height: 34px;
            padding: 0 14px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            background: #fff;
            cursor: pointer;
            transition: all .15s;

            &:hover {
                border-color: #3b82f6;
            }

            &:disabled {
                opacity: .6;
                cursor: not-allowed;
            }
        }
    }
}

/* 外置可定位按钮容器（如需） */
.tabs-outside {
    position: relative;
    background: transparent;
    border: 0;
}
.tab-btn { pointer-events: auto; cursor: pointer; }

/* 表格容器 - 使用 CSS 变量控制位置和尺寸 */
.table-wrap {
    /* 使用 CSS 变量控制表格容器的位置和尺寸 */
    position: absolute;
    left: var(--table-left, 80px);
    top: var(--table-top, 110px);
    width: var(--table-width, 1200px);
    height: var(--table-height, calc(100% - var(--table-top, 110px) - var(--table-bottom, 60px)));
    background: transparent;
    overflow: auto;

    /* 如果您想使用右下定位方式，可以取消下面的注释并注释掉上面的 width 和 height */
    /*
    right: var(--table-right, 80px);
    bottom: var(--table-bottom, 60px);
    */

    table {
        width: 100%;
        /* 行间距：使用分离模型并增加垂直间距 */
        border-collapse: separate;
        border-spacing: 0 8px;
        table-layout: fixed;

        thead th {
            position: sticky;
            top: 0;
            background: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(6px);
            z-index: 1;
            text-align: left;
            padding: 10px 12px;
            font-weight: 700;
            color: #6b7280;
        }

        th,
        td {
            padding: 12px 14px;
            margin: 0;
            vertical-align: middle;
            color: #fff;
            font-size: 25px;
        }

        /* 列宽：1=排名 2=国家名 3=城市数 4=积分总和 5=玩家列表(自适应) */
        th:nth-child(1), td:nth-child(1) { width: 72px; }
        th:nth-child(2), td:nth-child(2) { width: 200px; }
        th:nth-child(3), td:nth-child(3) { width: 110px; }
        th:nth-child(4), td:nth-child(4) { width: 160px; }

        /* 列表项背景颜色与 Leaderboard 保持一致 */
        tbody td {
            background: rgba(10, 20, 114, 0.45);
        }

        tbody tr:hover td {
            background: rgba(10, 20, 114, 0.6);
        }

        .center {
            text-align: center;
        }

        .strong {
            font-weight: 700;
        }

        .points {
            font-weight: 700;
            text-align: left;
            white-space: nowrap;
        }

        .country-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 玩家列（第5列） */
        td:nth-child(5) {
            overflow: hidden;
        }
    }

    .empty {
        text-align: center;
        color: #6b7280;
    }
}

/* 分页条 */
.pager {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 6px 12px 10px 12px;
    border-top: 1px solid #e5e7eb;
    background: rgba(255, 255, 255, .5);
    font-size: 13px;
    color: #6b7280;

    .left {
        color: #111827;
    }

    .right {
        .btn {
            height: 30px;
            padding: 0 12px;
            margin: 0 10px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            background: #fff;
            cursor: pointer;
            transition: all .15s;

            &:hover {
                border-color: #3b82f6;
            }

            &:disabled {
                opacity: .6;
                cursor: not-allowed;
            }
        }
    }
}

/* 玩家标签：嵌套写法，简化层级 */
.players {
    .tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px 10px;
    }

    .tag {
        display: inline-flex;
        align-items: center;
        gap: 10px;
        padding: 4px 8px; /* 缩小一些 padding */
        height: 44px; /* 适配更大的头像高度 */
        max-width: 100%;
        border: 1px solid #2563eb;
        /* 与 active 蓝色系一致 */
        border-radius: 999px;
        /* 胶囊形 */
        background: #3b82f6;
        /* 使用 active 的蓝色 */
        color: #fff;
        overflow: hidden;

        .avatar,
        .avatar-fallback {
            width: 36px;  /* 放大头像 */
            height: 36px; /* 放大头像 */
            border-radius: 50%;
            object-fit: cover;
            border: 1px solid #fff;
            flex: 0 0 auto;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            color: #fff;
            background: #1e40af;
            /* 深蓝底，非透明 */
        }

        .info {
            min-width: 0;
            /* 允许子项截断 */
            display: inline-flex;
            align-items: baseline;
            gap: 8px;

            .name {
                font-weight: 600;
                font-size: 18px; /* 玩家名字缩小一些（覆盖单元格默认字号） */
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                max-width: 16em;
                /* 限制昵称过长 */
            }

            .meta {
                font-size: 12px;
                color: #dbeafe;
                /* 浅蓝，非透明 */
                white-space: nowrap;
            }
        }
    }
}

/* 分页过渡动画（整页行切换） */
.page-enter-active,
.page-leave-active {
    transition: all .28s ease;
}

.page-enter-from {
    opacity: 0;
    transform: translateY(8px);
}

.page-leave-to {
    opacity: 0;
    transform: translateY(-8px);
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

/* ===========================================
   表格高度控制 - 自定义 CSS 变量示例
   =========================================== */

/* 示例1：小表格 */
.tabbed-table.small-table {
    --container-height: 600px;
    --table-height: 400px;
    --table-top: 80px;
    --table-bottom: 40px;
}

/* 示例2：大表格 */
.tabbed-table.large-table {
    --container-height: 1400px;
    --table-height: 1000px;
    --table-top: 120px;
    --table-bottom: 80px;
}

/* 示例3：自适应高度（使用 calc） */
.tabbed-table.auto-height {
    --table-height: calc(var(--container-height, 1058px) - var(--table-top, 110px) - var(--table-bottom, 60px) - 20px);
}

/* 示例4：紧凑布局 */
.tabbed-table.compact {
    --table-top: 60px;
    --table-bottom: 30px;
    --table-left: 40px;
    --table-right: 40px;
    --table-width: calc(100% - var(--table-left, 40px) - var(--table-right, 40px));
}
</style>
